package com.example.learn_spring_boot3.exception;

import com.example.learn_spring_boot3.utils.ResponseData;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

// 全局业务异常处理类
@RestControllerAdvice
@Order(1) // 这里把优先级弄高, 超过默认的全局异常, 则会优先触发这个
public class GlobalServiceExceptionHandler {
    // 捕获业务异常
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseEntity<ResponseData<Object>> exception(ServiceException e) {
        e.printStackTrace();

        // 获取到 code 和 message
        return ResponseEntity.ok(ResponseData.error(e.getCode(), e.getMessage(), null));
    }
}